<template>
    <view id="evaluation-task">
        <view class="card">
            <view class="card-title">
                <view class="icon-style el-icon-ali-goods"></view>
                <view class="title">评价商品</view>
            </view>
            <view class="card-content">
                <image class="goods-img" :src="taskList.goods_img" mode=""></image>
                <view class="goods-info">
                    <view class="goods-name">
                        店铺名称：
                        <text class="name">{{getShopName(taskList.platform_type)}}--{{taskList.shop_name}}</text>
                    </view>
                    <view class="goods-name">
                        订单号：
                        <text class="name">{{taskList.order_num}}</text>
                    </view>
                    <view class="goods-title">
                        {{taskList.goods_title}}
                    </view>
                </view>
            </view>
        </view>
        <view class="card">
            <view class="card-title">
                <view class="icon-style el-icon-ali-comments"></view>
                <view class="title">订单信息</view>
            </view>
            <view class="card-content">
                <view class="merchant-comments" v-if="taskList.order_num">
                    <view class="content">
                      淘宝号：{{taskList.tb_name}}
                      <br/>
                      订单号：{{taskList.order_num}}
                    </view>
                    <view class="btn-box">
                        <view class="comments-copy-btn" @click="copyOrderNum">复制</view>
                    </view>
                </view>
                <view class="default-comments" v-else>
					订单号异常
                </view>
            </view>
        </view>
        <view class="card">
            <view class="card-title">
                <view class="icon-style el-icon-ali-note-1"/>
                <view class="title"> 商家要求</view>
            </view>
            <view class="card-content">
                <view class="merchant-comments">
                    <view class="content">{{taskList.merchant_content}}</view>
                </view>
            </view>
        </view>
        <view class="card">
            <view class="card-title">
                <view class="icon-style el-icon-ali-comments"></view>
                <view class="title">评语</view>
            </view>
            <view class="card-content">
                <view class="merchant-comments" v-if="taskList.assess_content">
                    <view class="content">{{taskList.assess_content}}</view>
                    <view class="btn-box">
                        <view class="comments-copy-btn" @click="copyKeyWord(taskList.assess_content)">复制</view>
                    </view>
                </view>
                <view class="default-comments" v-else>
                    五星好评，评价自由发挥
                </view>
            </view>
        </view>
        <view class="card" v-if="imgArr.length > 0">
            <view class="card-title">
                <view class="icon-style el-icon-ali-show-img"></view>
                <view class="title">图片</view>
            </view>
            <view class="card-content">
                <view class="note">
                    注：如果图片加载缓慢或者加载不出来，请刷新重试
                    <text v-if="mobilePlatformType != 'APP'">或者点击图片区域！</text>
                </view>
                <view class="img-box">
                    <image class="show-img" @click="showImg(item.url)" v-for="(item, index) in imgArr"
                           :data-index="index" @load="imgLoading" :key="index"
                           :src="item.show ? item.url : '../../static/img/img_loading.png'"></image>
                </view>
                <view class="copy-video-url" @click="downloadImgToSave" v-if="mobilePlatformType=='APP'">点击下载图片</view>
                <view class="tips" v-else>
                    <view class="tips-icon el-icon-ali-note"></view>
                    <view class="text">长按保存图片</view>
                </view>
            </view>
        </view>
        <view class="card" v-if="taskList.video_url">
            <view class="card-title">
                <view class="icon-style el-icon-ali-video"></view>
                <view class="title">视频（视频无法下载的请复制链接到浏览器保存）</view>
            </view>
            <view class="card-content" v-if="mobilePlatformType=='APP'">

                <view class="video-box" @click="chooseImage">
                    <video class="video" :src="taskList.video_url" controls></video>
                </view>
                <view class="copy-video-url" @click="downloadVideo(taskList.video_url)">
                    点击下载视频
                </view>
            </view>
            <view class="card-content" v-else>
                <!--				<view class="note">-->
                <!--					复制视频链接后，长按下面的二维码进入小程序，进行下载-->
                <!--				</view>-->
                <!--				<view class="video-box" @click="chooseImage">-->
                <!--					<image class="xiao-v-img" src="../../static/img/xiaoV.png" mode=""></image>-->
                <!--				</view>-->
                <view class="copy-video-url" style="margin-bottom: 20upx">
                    <a style="text-decoration:none;color: #ffffff;" :href="taskList.video_url">下载视频</a>
                </view>
                <view class="copy-video-url" @click="copyKeyWord(taskList.video_url)">
                    复制视频链接（请复制链接到浏览器下载）
                    <!--<a style="text-decoration:none;color: #ffffff;" :href="taskList.video_url">下载视频</a>-->
                </view>
                <!--				<view class="copy-video-url" @click="saveVideo">-->
                <!--					复制视频链接-->
                <!--				</view>-->
            </view>
        </view>
        <view class="card">
            <view class="card-title">
                <view class="icon-style el-icon-ali-show-img"></view>
                <view class="title">截图上传</view>
            </view>
            <view class="card-content">
                <view class="note">
                    请截图完成后记得发表评价！务必规范上传评价完成后的评价截图，截图错误不给佣金。
                </view>
                <view class="upload-box" ref="uploads" @click="chooseImage">
                    <view class="img-upload">
                        <view class="upload-icon el-icon-ali-upload-img" v-if="imgUrl == ''"></view>
                    </view>
					<view class="img-example">
						<image :src="exampleImageSrc.success" @click.stop="lookImage(exampleImageSrc.success)" @error="imageError"></image>
					</view>
                </view>
            </view>
        </view>
        <button class="sumbit-btn" :loading="loading" :disabled="loading" @click="completeTask">提交任务</button>
    </view>
</template>

<script>
    import {
        apiAssessTaskDetail,
        apiPushSubmitAssess,
        apiUploadToken
    } from '../../../http/apis.js'
    import {
        mapState
    } from 'vuex'
    import qiniuUploader from '../../components/qiniu/qiniuUploader.js';

    export default {
        computed: {
            ...mapState(['token'])
        },
        data() {
            return {
              exampleImageSrc: {
                success: "../../static/img/comment_home.png",
                error: "../../static/img/comment_append.png"
              },// 截图示例
              taskList: {},
              imgUrl: '',
              loading: false,
              storeName: {
                  1: '淘宝',
                  2: '天猫',
                  3: '京东',
                  4: '1688',
                  13: '唯品会',
                  15: '拼多多',
                  20: '抖音'
              },
              pushTaskId: null,
              uploadToken: '',
              isCopyVideo: false,
              imgArr: [],
              mobilePlatformType: uni.getStorageSync('mobilePlatformType')
          }
        },
        onLoad(option) {
            this.pushTaskId = option.id;
            this.getEvaluationData()
            apiUploadToken({}).then(res => {
                if (res.data.code == 1) {
                    this.uploadToken = res.data.msg
                }
            }).catch(res => {
                this.$msg.showToast(res.data.msg)
            })
        },
        onShow() {

        },
        methods: {
          imageError: function(e) {
            this.$msg.showToast("截图示例图片丢失")
          },
          lookImage(url) {
            // 预览图片
            uni.previewImage({
              current: url,
              urls: [this.exampleImageSrc.success],
              // longPressActions: {
              // 	itemList: ['发送给朋友', '保存图片', '收藏'],
              // 	success: function(data) {
              // 		console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
              // 	},
              // 	fail: function(err) {
              // 		console.log(err.errMsg);
              // 	}
              // }
            });
          },
          getEvaluationData() {
              //this.$isClick(true);
              apiAssessTaskDetail({
                  token: this.token,
                  pushTaskId: this.pushTaskId
              }).then(res => {
                  //this.$isClick(false);
                  if (res.data.code == 1) {
                      this.taskList = res.data.msg
                      var statusArr = [1, 2]
                      if (statusArr.indexOf(this.taskList.status) < 0) {
                          this.$msg.showToast('任务不存在')
                          setTimeout(() => {
                              uni.switchTab({
                                  url: './taskList'
                              });
                          }, 1000)
                      }
                      this.taskList.video_url = this.taskList.video_url == null ? '' : this.taskList.video_url
                      if (this.taskList.img_urls) {
                          var imgUrls = this.taskList.img_urls.split(',')
                          for (var i in imgUrls) {
                              this.imgArr.push({
                                  url: imgUrls[i],//?imageMogr2/size-limit/15k!/crop/38x100
                                  show: false
                              })
                          }
                      }
                  }
              }).catch(res => {
                  this.$msg.showToast(res.data.msg)
              })
          },
          getShopName(type) {
              return this.storeName[type]
          },
          showImg(url) {
              let imgArr = this.imgArr.map(item => item.url)
              // 预览图片
              uni.previewImage({
                current: url,
                urls: imgArr,
                fail() {
                  this.$msg.showToast("图片预览异常")
                }
              });
              // window.location.href = url
          },
          imgLoading(e) {
              setTimeout(() => {
                  this.imgArr[e.target.dataset.index].show = true
              }, 1000)
          },
          copyKeyWord(val) {
              if (!val) return this.$msg.showToast('没有内容复制')
              uni.setClipboardData({
                  data: val,
                  success: () => {
                      this.$msg.showToast('复制成功')
                  },
                  fail: () => {
                      this.$msg.showToast('复制失败')
                  }
              });
          },
          copyOrderNum() {
              uni.setClipboardData({
                  data: this.taskList.order_num,
                  success: () => {
                      this.$msg.showToast('复制成功')
                  },
                  fail: () => {
                      this.$msg.showToast('复制失败')
                  }
              });
          },
          chooseImage() {
              var that = this
              uni.chooseImage({
                  count: 1,
                  sizeType: ['origial'],
                  success: res => {
                      const uploads = that.$refs.uploads.$el;
                      const uploadBox = uploads.querySelector('.img-upload');
                      uploadBox.style.backgroundImage = `url('${res.tempFilePaths[0]}')`;
                      uploadBox.className = 'img-upload';
                      // that.files[type].filePath = res.tempFilePaths[0];
                      that.uploadImg(res, res.tempFiles[0].size > 1570000);
                  },
                  fail: function () {
                      that.$msg.showToast('载入图片失败，请稍后再试')
                  }
              });
          },
          uploadImg(typeimg, fileSize) {
              var that = this;
              uni.showLoading({
                  title: '上传中',
                  mask: true
              })
              uni.getImageInfo({
                  src: typeimg.tempFilePaths[0],
                  success(res) {
                      // 			let canvasWidth = res.width //图片原始长宽
                      // 			let canvasHeight = res.height
                      // 			let img = new Image()
                      // 			img.src = res.path
                      // 			let canvas = document.createElement('canvas');
                      // 			let ctx = canvas.getContext('2d')
                      // 			let scale = res.height/res.width
                      // 			canvas.width = fileSize == true ? 500 : canvasWidth
                      // 			canvas.height = fileSize == true ? 500*scale : canvasHeight
                      // 			ctx.drawImage(img, 0, 0, fileSize == true ? 500 : canvasWidth , fileSize == true ? 500*scale : canvasHeight )//fileSize == true ? 300 : canvasHeight / 2

                      // 			canvas.toBlob(function(fileSrc) {
                      // 				let imgSrc = window.URL.createObjectURL(fileSrc)
                      let imgSrc = res.path;
                      var random = Math.floor(Math.random() * (1000 - 1)) + 1
                      var timestamp = new Date().getTime();
                      var name = imgSrc.substring(imgSrc.lastIndexOf("-") + 1);
                      var key = name + random.toString() + timestamp.toString() + '.png'
                      qiniuUploader.upload(
                          imgSrc,
                          res => {
                              //图片上传完成后返回值
                              that.imgUrl = res.imageURL;
                              that.$msg.showToast('上传成功')
                          },
                          error => {
                              // resolve(error)
                              uni.hideLoading()
                              that.$msg.showToast('上传失败')
                          },
                          {
                              region: that.GLOBAL.REGION_VALUE, // （必须填写正确）ECN, SCN, NCN, NA, ASG，分别对应七牛的：华东，华南，华北，北美，新加坡 5 个区域
                              domain: that.GLOBAL.QINIU_URL, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL                                         字  段。否则需要自己拼接
                              key: 'evaluation/' + key, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
                              // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
                              uptoken: that.uploadToken // 由其他程序生成七牛 uptoken
                          },
                          res => {
                              //上传进度
                              if (res.progress === 100) {
                                  uni.hideLoading()
                              }
                          }
                      );
                      // })
                  }
              })

          },
          saveVideo() {
              this.isCopyVideo = false
              uni.setClipboardData({
                  data: this.taskList.video_url,
                  success: () => {
                      this.isCopyVideo = true
                      this.$msg.showToast('复制成功')
                  },
                  fail: () => {
                      this.isCopyVideo = false
                      this.$msg.showToast('复制失败')
                  }
              });

          },
          completeTask() {
              // if(this.mobilePlatformType != 'APP'){
              // 	if(!this.isCopyVideo && this.taskList.video_url){
              // 		uni.showToast({title:'请先复制链接，并长按二维码进入小程序，下载视频',duration: 1000,icon:'none'})
              // 		return
              // 	}
              // }
              if (this.imgUrl == '') {
                  uni.showToast({title: '请先上传评价截图', duration: 1000, icon: 'none'})
                  return
              }
              if (this.imgUrl.indexOf('evaluation') < 0) {
                  uni.showToast({title: '上传评价图片失败，请重新上传', duration: 1000, icon: 'none'})
                  return
              }
              uni.showLoading({
                  title: '提交中...',
                  mask: true
              })
              this.loading = true
              apiPushSubmitAssess({
                  token: this.token,
                  pushTaskId: this.pushTaskId,
                  pushImgUrl: this.imgUrl
              }).then(res => {
                  uni.hideLoading()
                  this.loading = false
                  if (res.data.code == 1) {
                      this.$msg.showToast(res.data.msg)
                      setTimeout(() => {
                          uni.switchTab({
                              url: './taskList'
                          });
                      }, 500)
                  } else {
                      this.$msg.showToast(res.data.msg)
                  }
              }).catch(res => {
                  uni.hideLoading()
                  this.loading = false
                  this.$msg.showToast(res.data.msg)
              })
          },
          //APP下载图片
          batchSaveImg() {
              uni.showLoading({
                  title: '下载中',
                  mask: true
              })
              return new Promise((resolve) => {
                  for (var i in this.imgArr) {
                      if (uni.getStorageSync('mobilePlatformType') == 'APP') {
                          let filename = Math.random() + ".png"
                          console.log(filename)
                          plus.downloader.createDownload(this.imgArr[i].url, {
                              filename: "_downloads/" + filename
                          }, (download, status) => {
                              if (status == 200) {//下载成功
                                  plus.gallery.save(download.filename, () => {
                                      if (i == this.imgArr.length - 1) {
                                          resolve(download);
                                      }

                                  })
                              }
                          }).start()
                      }
                  }
              })
          },
          downloadImgToSave() {
              this.batchSaveImg().then(() => {
                  uni.hideLoading();
                  this.$msg.showToast('下载成功')
              })
          },
          //APP下载视频
          downloadVideo(url) {
              uni.showLoading({
                  title: '下载中',
                  mask: true
              })
              let filename = Math.random() + ".mp4"
              plus.downloader.createDownload(url, {
                  filename: "_downloads/" + filename
              }, (download, status) => {
                  if (status == 200) {//下载成功
                      plus.gallery.save(download.filename, () => {
                          uni.hideLoading();
                          uni.showToast({
                              title: '下载成功！'
                          });
                      }, (e) => {
                          console.log(e)
                      })
                  }
              }).start()
          },
        }
    }
</script>

<style lang="scss">
    page {
        background: #f5f5f5;
    }

    #evaluation-task {
        .card {
            padding: 48upx 30upx;
            background: #FFFFFF;
            margin-bottom: 24upx;

            .card-title {
                color: $theme-color;

                .icon-style {
                    display: inline-block;
                }

                .title {
                    display: inline-block;
                    font-size: 30upx;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #FF5001;
                    line-height: 28upx;
                }
            }

            .card-content {

                margin-top: 24upx;

                .goods-img {
                    width: 100upx;
                    height: 100upx;
                }

                .goods-info {
                    font-size: 28upx;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #666666;
                    line-height: 28upx;
                    margin-left: 20upx;
                    display: inline-block;
                    vertical-align: top;
                    width: 80%;

                    .goods-name {
                        margin-top: 12upx;

                        .name {
                            font-size: 28upx;
                            font-weight: 500;
                            color: #333333;
                            line-height: 28upx;
                        }
                    }

                    .goods-title {
                        font-size: 24upx;
                        color: #999999;
                        line-height: 28upx;
                        margin-top: 24upx;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                    }
                }

                .merchant-comments {
                    .content {
                        font-size: 28upx;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #333333;
                        line-height: 44upx;
                        display: inline-block;
                    }

                    .btn-box {
                        text-align: right;
                    }

                    .comments-copy-btn {
                        font-size: 22upx;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: $theme-color;
                        line-height: 32upx;
                        border-radius: 18upx;
                        border: 1px solid $theme-color;
                        display: inline-block;
                        padding: 2upx 20upx;
                        // float: right;
                    }
                }

                .default-comments {
                    font-size: 28upx;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #333333;
                    line-height: 44upx;
                }

                .note {
                    font-size: 28upx;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #666666;
                    line-height: 44upx;
                }

                .img-box {
                    margin-top: 24upx;

                    .show-img {
                        width: 200upx;
                        height: 260upx;
                        margin-bottom: 14upx;
                        margin-right: 14upx;
                    }
                }

                .tips {
                    font-size: 24upx;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: $theme-color;
                    line-height: 24upx;
                    margin-top: 10upx;

                    .tips-icon {
                        display: inline-block;
                        font-size: 28upx;
                        margin-right: 4upx;
                    }

                    .text {
                        display: inline-block;
                        vertical-align: text-top;
                        margin-top: 2px;
                    }
                }

                .video-box {
                    text-align: center;

                    .xiao-v-img {
                        width: 260upx;
                        height: 260upx;
                        margin-bottom: 20upx;
                    }

                    .video {
                        width: 200upx;
                        height: 260upx;
                    }
                }

                .copy-video-url {
                    background: $theme-background-color;
                    color: #FFFFFF;
                    font-size: 28upx;
                    padding: 10upx 26upx;
                    border-radius: 10upx;
                    margin: 0 auto;
                    text-align: center;
                    width: 200upx;
                }

                .upload-box {
                    margin-top: 24upx;

                    .img-upload {
						float: left;
                        border: 0.5px dotted #666666;
                        /*position: relative;*/
                        width: 120px;
                        height: 160px;
                        box-sizing: border-box;
                        background-size: cover;
                        background-repeat: no-repeat;
                        background-position: center;

                        .upload-icon {
                            font-size: 25px;
                            line-height: 160px;
                            text-align: center;
                            color: #666666;
                        }
                    }
					.img-example {
						float: left;
						margin-left: 20upx;
						width: 120px;
						height: 160px;
						image {
							display: block;
							width: 100%;
							height: 100%;
						}
					}
					&:after {
						content: '';
						height: 0;
						line-height: 0;
						display: block;
						visibility: hidden;
						clear: both;
					}
                }
            }
        }

        .sumbit-btn {
            margin: 32upx;
            height: 96upx;
            background: $theme-background-color;
            border-radius: 10upx;
            font-size: 32upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: rgba(255, 255, 255, 1);
            line-height: 96upx;
            margin-top: 48upx;
        }
    }
</style>
